package com.gs.m_login

import android.content.Context
import android.os.Handler
import android.os.Looper
import com.gs.common.BaseStateCallback
import com.gs.common.constant.StateCode
import com.gs.common.sqlite.UserSqliteOpenHelper
import com.gs.m_home.model.MineModel

class LoginPersistent(context: Context) {

    private val loginModel by lazy { LoginModel.getInstance(context) }
    private val handler = Handler(Looper.getMainLooper())

//    fun checkUserState(usernameOrPhoneNum: String, callback: OnCheckUserStateCallback) {
//
//    }

    /**
     * 进行登录操作
     */
    fun doLogin(usernameOrPhoneNum: String, password: String, callback: OnDoLoginStateCallback) {
        Thread{
            // 查询数据耗时操作
            loginModel.login(usernameOrPhoneNum, password) {
                when (it) {
                    StateCode.STATE_LOADING -> {
                        handler.post {
                            callback.onLoginLoading()
                        }
                    }
                    StateCode.STATE_SUCCESS -> {
                        handler.post {
                            callback.onLoginSuccess()
                        }
                    }
                    StateCode.STATE_FAILED -> {
                        handler.post {
                            callback.onLoginFailed()
                        }
                    }
                    StateCode.NETWORK_ERROR -> {
                        handler.post {
                            callback.onNetworkError()
                        }
                    }
                    StateCode.SERVER_ERROR -> {
                        handler.post {
                            callback.onServerError()
                        }
                    }
                    StateCode.UNKNOWN_ERROR -> {
                        handler.post {
                            callback.onUnknownError()
                        }
                    }
                }
            }
        }.start()
    }

    interface OnDoLoginStateCallback: BaseStateCallback {
        fun onLoginLoading(){}

        fun onLoginSuccess()

        fun onLoginFailed()
    }

//    interface OnCheckUserStateCallback {
//        fun onNotExist()
//        fun onExist()
//    }

    companion object{
        private var instance: LoginPersistent? = null
        fun getInstance(context: Context): LoginPersistent {
            if (instance == null) {
                synchronized(this::class) {
                    if (instance == null) {
                        instance = LoginPersistent(context)
                    }
                }
            }
            return instance!!
        }
    }
}